#ifndef UPDATEMANAGER_H
#define UPDATEMANAGER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QFile>
#include <QTimer>
#include <QJsonObject>
#include <QUrl>
#include <QStandardPaths>
#include "versionmanager.h"
#include "app_version.h"
#include "secureapimanager.h"

class UpdateManager : public QObject
{
    Q_OBJECT

public:
    explicit UpdateManager(QObject* parent = nullptr);
    ~UpdateManager();

    // 更新检查
    void checkForUpdates(bool silent = false);
    bool hasUpdateAvailable() const;
    VersionManager::UpdateInfo getUpdateInfo() const;

    // 更新操作
    void startUpdate();
    void pauseDownload();
    void resumeDownload();
    void cancelUpdate();

    // 状态查询
    bool isDownloading() const { return m_isDownloading; }
    bool isPaused() const { return m_isPaused; }
    int getDownloadProgress() const { return m_downloadProgress; }
    QString getDownloadSpeed() const { return m_downloadSpeed; }
    QString getDownloadPath() const;

signals:
    void updateAvailable(const VersionManager::UpdateInfo& info);
    void downloadProgress(int progress, qint64 received, qint64 total);
    void downloadFinished(const QString& filePath);
    void downloadError(const QString& error);
    void updateFinished(bool success);
    void serverVersionReceived(const QString& version);

private slots:
    void onRequestFinished();
    void onDownloadProgress(qint64 received, qint64 total);
    void onDownloadFinished();
    void onDownloadError(QNetworkReply::NetworkError error);
    void onRetryTimer();

private:
    // 网络相关
    QNetworkAccessManager* m_networkManager;
    QNetworkReply* m_currentReply;
    QString m_downloadPath;
    QFile* m_outputFile;

    // 状态管理
    VersionManager::UpdateInfo m_currentUpdateInfo;
    bool m_isDownloading;
    bool m_isPaused;
    int m_downloadProgress;
    QString m_downloadSpeed;
    qint64 m_downloadStartTime;
    qint64 m_lastReceivedBytes;

    // 重试机制
    QTimer* m_retryTimer;
    int m_retryCount;
    static const int MAX_RETRY_COUNT = 3;
    static const int RETRY_DELAYS[MAX_RETRY_COUNT];

    // 方法
    bool verifyDownloadedFile(const QString& filePath);
    void performUpdate(const QString& filePath);
    void backupCurrentVersion();
    void restoreBackup();
    void showUpdateDialog();
    void checkServerVersion();
    void parseLoginResponse(const QJsonObject& jsonResponse);

    // 错误处理
    void handleError(const QString& error);
    void scheduleRetry();
    QString getErrorMessage(QNetworkReply::NetworkError error);

    // 文件操作
    bool createDownloadDirectory();
    QString calculateMD5(const QString& filePath);
    void cleanDownloadFiles();
    void cleanupDownload();
};

#endif // UPDATEMANAGER_H